package com.wnxy.filter;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wnxy.dto.LoginDto;
import com.wnxy.dto.ManagerDetail;
import com.wnxy.dto.QQInfoDto;
import com.wnxy.model.Manager;
import com.wnxy.model.ManagerRole;
import com.wnxy.service.ManagerRoleService;
import com.wnxy.service.ManagerService;
import com.wnxy.service.impl.ManagerRoleServiceImpl;
import com.wnxy.service.impl.PhoneFailureHandler;
import com.wnxy.service.impl.PhoneSuccessHandler;
import com.wnxy.service.impl.QQSuccessHandler;
import com.wnxy.token.PhoneAuthenticationToken;
import com.wnxy.token.QQAuthenticationToken;
import com.wnxy.util.BeanCopyUtil;
import com.wnxy.util.DateUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.lang.Nullable;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.Assert;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class QQAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
    private static final AntPathRequestMatcher DEFAULT_ANT_PATH_REQUEST_MATCHER = new AntPathRequestMatcher("/qqlogin", "GET");
    //    private boolean postOnly = true;
    private ManagerService managerService;
    private ManagerRoleService managerRoleService;
    private RestTemplate rt=new RestTemplate();
    private ObjectMapper om=new ObjectMapper();
    //    private StringRedisTemplate srt;
    public QQAuthenticationFilter(ManagerService managerService,ManagerRoleService managerRoleService) {
        super(DEFAULT_ANT_PATH_REQUEST_MATCHER);
        this.managerService = managerService;
        this.managerRoleService=managerRoleService;
    }
    public QQAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(DEFAULT_ANT_PATH_REQUEST_MATCHER, authenticationManager);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException{
        String code=request.getParameter("code");
        String url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id=101780702&client_secret=be3cf79b89eafe3f0b8f90462aed8065&code=" + code + "&redirect_uri=http://www.pawntest.com/qqlogin&state=test";
        String value = rt.getForObject(url, String.class);
        String token=value.substring(value.indexOf("=")+1,value.indexOf("&"));
        url="https://graph.qq.com/oauth2.0/me?access_token="+token;
        value = rt.getForObject(url, String.class);
        String openId=value.substring(value.lastIndexOf(":")+2,value.lastIndexOf("\""));
        url="https://graph.qq.com/user/get_user_info?access_token="+token+"&oauth_consumer_key=101780702&openid="+openId;
        String js = rt.getForObject(url, String.class);
        QQInfoDto qq = null;
        try {
            qq = om.readValue(js, QQInfoDto.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        Manager manager = managerService.getOne(new QueryWrapper<Manager>().eq("open_id", openId));
        if(manager==null){
            throw new InternalAuthenticationServiceException("该用户不存在"+openId+js);
        }
        LoginDto ld = BeanCopyUtil.copyProperties(manager, LoginDto.class);
            ld.setOpenId(openId);
            ld.setManagerQqName(qq.getNickname());
            ld.setManagerImg(qq.getFigureurl_1());
        ManagerDetail managerDetail = BeanCopyUtil.copyProperties(ld, ManagerDetail.class);

        Integer roleId = managerRoleService.getOne(new QueryWrapper<ManagerRole>().eq("manager_id", managerDetail.getManagerId())).getRoleId();
        managerDetail.setMangerRoleId(roleId);
        System.out.println(managerDetail);
        QQAuthenticationToken authRequest = new QQAuthenticationToken(managerDetail, null, null);
        this.setDetails(request, authRequest);
        return authRequest;
    }



    protected void setDetails(HttpServletRequest request, QQAuthenticationToken authRequest) {
        authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
    }
}
